import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 043. 往完全二叉树添加节点
 * @author: WXY
 * @create: 2022-12-31 14:14
 * @Version 1.0
 **/
public class offer_fourteen3_CBTInserter {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class CBTInserter {
        Queue<TreeNode> queue = new ArrayDeque<>();
        TreeNode root;

        public CBTInserter(TreeNode root) {
            this.root = root;
            queue.offer(root);
            while (queue.peek().right != null && queue.peek().left != null) {
                TreeNode node = queue.poll();
                queue.offer(node.left);
                queue.offer(node.right);
            }
        }

        public int insert(int v) {
            TreeNode node = queue.peek();
            if (node.left == null) {
                node.left = new TreeNode(v);
            } else {
                node.right = new TreeNode(v);
                queue.poll();
                queue.offer(node.left);
                queue.offer(node.right);
            }
            return node.val;
        }

        public TreeNode get_root() {
            return root;
        }
    }
}
